package com.xw.picture.analysis.controller;

import com.xw.picture.analysis.entity.ImageInfo;
import com.xw.picture.analysis.util.FileUtil;
import com.xw.picture.analysis.util.ImageUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @author ：xiongwei
 * @date ：Created in 2020/11/22 17:18
 */
@Slf4j
@RestController
@RequestMapping("picture")
@Api(value = "图片操作", tags = "图片操作相关API")
public class PictureController {

    @PostMapping(value = "/uploadImage")
    @ApiOperation(value = "图片传输", notes = "图片上传")
    public String uploadImage(HttpServletRequest request,@RequestBody ImageInfo imageInfo) {

        log.info("imageInfo.getImageData() = {}", imageInfo.getImageData());
        ImageUtil.convertBase64ToFile(imageInfo.getImageData(), FileUtil.currentFilePath()+"image",imageInfo.getImageName());
        return "uploading uploadImage";
    }

    /**
     * 处理文件上传
     */
    @PostMapping(value = "/upload")
    @ApiOperation(value = "文件上传", notes = "文件上传")
    public String uploading(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        long startTime = System.currentTimeMillis();
        String fileName = request.getHeader("fileName");
        log.info("fileName = {}, getOriginalFilename = {}", fileName, file.getOriginalFilename());
        if (StringUtils.isEmpty(fileName)) {
            return "文件名为空";
        }
        String filepath = System.getProperty("user.dir") + File.separator + "image" + File.separator;
        File targetFile = new File(filepath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        try (FileOutputStream out = new FileOutputStream(filepath + fileName);) {
            out.write(file.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("文件上传失败!");
            return "uploading failure";
        }
        long endTime = System.currentTimeMillis();
        log.info("文件上传成功!");
        log.info("startTime = {}!", startTime);
        log.info("endTime = {}!", endTime);
        return "uploading success";
    }

    @GetMapping("/download")
    @ApiOperation(value = "文件下载", notes = "文件下载")
    public void downLoad(HttpServletResponse response) throws UnsupportedEncodingException {
        String filename = "JAVA核心知识点整理.pdf";
        String filePath = "D:/file";
        File file = new File(filePath + "/" + filename);
        if (file.exists()) {
            response.setContentType("application/octet-stream");
            response.setHeader("content-type", "application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(filename, "utf8"));
            byte[] buffer = new byte[1024];
            //输出流
            OutputStream os = null;
            try (FileInputStream fis = new FileInputStream(file);
                 BufferedInputStream bis = new BufferedInputStream(fis);) {
                os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
